// @/components/composables/useCategoryPage.ts
import { ref, onMounted, watch } from 'vue'
import { router } from '@/router/index'
import myaxios from '@/auth/auth.service'
import {showToastMessage} from "@/utils/message"


// 定义类别类型
interface Category {
  id: number
  name: string
  description: string | null
  address: string | null
  construction_age: string | null
  construction_type: string | null
  layout_orientation: string | null
  protection_level: string | null
  image_base64: string | null
  created_at: string
  updated_at: string | null
  relic_count?: number
}

// 定义组件状态类型
type ComponentState = 'loading' | 'loaded' | 'empty' | 'error'

export function useCategoryPage() {
  const currentPage = ref(1)
  const pageSize = ref(5)
  const searchKeyword = ref('')
  const categories = ref<Category[]>([])
  const total = ref(0)
  const totalPages = ref(0)
  const componentState = ref<ComponentState>('loading')

  const loadData = async (page = 1, search = '') => {
    try {
      componentState.value = 'loading'
      const params = {
        page,
        page_size: pageSize.value,
        search,
      }
      const response = await myaxios.fetchCategories(params)
      showToastMessage('success',"数据加载成功")
      const data = response.data
      categories.value = data.data || []
      total.value = data.count || 0
      totalPages.value = data.pages || 0
      currentPage.value = page
      componentState.value = categories.value.length === 0 ? 'empty' : 'loaded'
      return true
    } catch (error) {
      console.error(`加载第${page}页类别数据失败:`, error)
      componentState.value = 'error'
      showToastMessage('error',"数据加载失败，请重试")
      return false
    }
  }

  const reloadData = () => {
    console.log('用户触发类别数据重新加载')
    loadData(currentPage.value, searchKeyword.value)
  }
  const goToUser = () => {
    router.push('/personalinfo')
  }
  const handleSearch = () => {
    if (searchKeyword.value.trim() === '') {
      loadData(1, '')
    } else {
      loadData(1, searchKeyword.value.trim())
    }
  }

  const handleImageError = (category: Category) => {
    console.error(`类别图片加载失败: ${category.image_base64}`)
    if (!category.imageErrorReported) {
      category.imageErrorReported = true
    }
  }

  const initData = async () => {
    console.log('初始化类别页面数据...')
    currentPage.value = 1
    searchKeyword.value = ''
    categories.value = []
    total.value = 0
    totalPages.value = 0
    await loadData(1)
  }

  onMounted(async () => {
    console.log('类别组件挂载，初始化数据...')
    await initData()
  })

  watch(currentPage, (newPage, oldPage) => {
    if (newPage !== oldPage) {
      loadData(newPage, searchKeyword.value.trim())
    }
  })

  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }

  const goToEdit = (id: number) => {
    router.push(`/category/edit/${id}`)
  }

  const goToAdd = () => {
    router.push('/category/add')
  }

  const goToMainPage = (categoryId: number, categoryName: string) => {
    router.push({
      path: '/mainpage/',
      query: { categoryid: categoryId, categoryname: categoryName },
    })
  }

  const deleteCategory = async (id: number) => {
    if (!window.confirm('确定要删除该类别吗？删除后相关文物也会全部删除')) {
      return
    }
    try {
      await myaxios.deleteCategory(id)
      showToastMessage('success',"删除成功")
      await loadData(currentPage.value, searchKeyword.value)
    } catch (error) {
      console.error('删除类别失败:', error)
      showToastMessage('error',"删除失败，请重试")
    }
  }

  const handlePageChange = (page: number) => {
    currentPage.value = page
  }

  const handlePageSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
    loadData()
  }

  const formatDate = (dateString: string) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  return {
    currentPage,
    pageSize,
    searchKeyword,
    categories,
    total,
    totalPages,
    componentState,
    reloadData,
    handleSearch,
    handleImageError,
    goHome,
    goToCategory,
    goToEdit,
    goToAdd,
    deleteCategory,
    handlePageSizeChange,
    handlePageChange,
    formatDate,
    goToMainPage,
    goToUser,
  }
}
